﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.UI;

namespace DMS.Business.Utility
{
    public class RequestHelper
    {
        private const string ErrorPage = "/error.aspx";

        public static void RedirectErrorPage(Page page,string errorInfo)
        {
            LogHelper.LogException(new Exception(errorInfo));
            page.Response.Redirect(ErrorPage + "?info=" + errorInfo);
        }

        /// <summary>
        /// 使用Request对象获取指定参数的值并转换成指定类型
        /// </summary>
        /// <typeparam name="T">要转换的类型</typeparam>
        /// <param name="paramName">参数名</param>
        /// <returns></returns>
        public static T Get<T>(string paramName)
        {
            string value = HttpContext.Current.Request.Form[paramName];
            Type type = typeof(T);
            object result;
            try
            {
                result = Convert.ChangeType(value, type);
            }
            catch
            {
                result = default(T);
            }
            return (T)result;
        }

        /// <summary>
        /// 将页面表单字段封装成指定类型的实体对象并返回
        /// </summary>
        /// <typeparam name="T">希望封装成的对象类型</typeparam>
        /// <returns>封装后的对象实体</returns>
        public static T GetEntity<T>() where T : new()
        {
            T entity = new T();
            string temp;
            Type objectType = typeof (T);

            if (HttpContext.Current.Cache[objectType.ToString()] == null)
            {
                HttpContext.Current.Cache[objectType.ToString()] = objectType.GetProperties();
            }

            foreach (PropertyInfo pInfo in (PropertyInfo[])HttpContext.Current.Cache[objectType.ToString()])
            {
                temp = HttpContext.Current.Request.Form[pInfo.Name];
                if (temp != null)
                {
                    try
                    {
                        pInfo.SetValue(entity, Convert.ChangeType(temp.Trim(), pInfo.PropertyType), null);
                    }
                    catch
                    {
                    }
                }
            }
            return entity;
        }
    }
}
